Micron Document




Conditional (computer programming)
part 5/26 · 46.2 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

The "dangling else" problem

The else keyword is made to target a specific if–then statement preceding it, but for nested if–then statements, classic programming languages such as ALGOL 60 struggled to define which specific statement to target. Without clear boundaries for which statement is which, an else keyword could target any preceding if–then statement in the nest, as parsed.

if a then if b then s else s2

can be parsed as

if a then (if b then s) else s2

or

if a then (if b then s else s2)

depending on whether the else is associated with the first if or second if. This is known as the dangling else problem, and is resolved in various ways, depending on the language (commonly via the end if statement or {...} brackets).

Else if

By using else if, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.

if condition then
-- statements
elseif condition then
-- more statements
elseif condition then
-- more statements;
...
else
-- other statements;
end if;

For example, for a shop offering as much as a 30% discount for an item:

if discount < 11% then
print (you have to pay $30)
elseif discount < 21% then
print (you have to pay $20)
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────